import React, { useEffect, useRef } from "react";

const StarfieldCanvas: React.FC = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (canvas) {
      const context = canvas.getContext("2d");
      if (context) {
        const width = (canvas.width = window.innerWidth);
        const height = (canvas.height = window.innerHeight);

        const stars: { x: number; y: number; size: number }[] = [];
        for (let i = 0; i < 25; i++) {
          stars.push({
            x: Math.random() * width,
            y: Math.random() * height,
            size: Math.random() * 3,
          });
        }

        function animate() {
          context!.fillStyle = "rgba(0, 0, 0, 0.05)";
          context!.fillRect(0, 0, width, height);

          context!.fillStyle = "white";
          stars.forEach((star) => {
            context!.beginPath();
            context!.arc(star.x, star.y, star.size, 0, Math.PI * 2);
            context!.fill();

            star.x -= 0.5 + star.size / 10;
            if (star.x < 0 || star.x > width) {
              star.x = width - star.x;
            }
          });

          requestAnimationFrame(animate);
        }

        animate();
      }
    }

    return () => {
      // Cleanup
    };
  }, []);

  return (
    <canvas
      ref={canvasRef}
      style={{ position: "absolute", top: 0, left: 0, zIndex: -1 }}
    />
  );
};

export default StarfieldCanvas;
